package com.cluck.alipay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.cluck.alipay.config.AlipayProperties;
import com.cluck.alipay.entity.Order;
import com.cluck.alipay.service.OrderService;
import com.lly835.bestpay.config.AliPayConfig;
import com.lly835.bestpay.config.WxPayConfig;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * 支付宝支付控制器
 */
@Controller
@RequestMapping("/alipay")
@Slf4j
public class AliPayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AlipayProperties alipayProperties;

    @PostMapping("/pay")
    public void pay(Order order, HttpServletResponse response) throws Exception {

        //生成订单号
        String orderNo = UUID.randomUUID().toString();

        Integer totalAmount = 0; //支付总金额
        String subject = ""; //订单名称
        String body = ""; //商品描述

        switch (order.getProductId()) {
            case 1:
                totalAmount= 9;
                subject = "请我喝杯奶茶";
                body = "09元-请我喝杯奶茶";
                break;
            case 2:
                totalAmount= 29;
                subject = "请我吃肯德基";
                body = "29元-请我吃肯德基";
                break;
            case 3:
                totalAmount= 49 ;
                subject = "请我吃顿饭";
                body = "49元-请我吃顿饭";
                break;
            default:
                totalAmount= 49;
                subject = "请我吃顿饭";
                body = "49元-请我吃顿饭";
                break;
        }

        order.setOrderNo(orderNo);
        order.setSubject(subject);
        order.setTotalAmount(new BigDecimal(totalAmount));
        order.setBody(body);

        //保存订单
        orderService.save(order);

        /*//发起支付
        alipayClient(order1, response);*/

        //支付宝配置
        AliPayConfig aliPayConfig = new AliPayConfig();
        aliPayConfig.setAppId(alipayProperties.getAppid());
        aliPayConfig.setPrivateKey(alipayProperties.getRsa_private_key());
        aliPayConfig.setAliPayPublicKey(alipayProperties.getAlipay_public_key());
        aliPayConfig.setReturnUrl(alipayProperties.getReturn_url());
        aliPayConfig.setNotifyUrl(alipayProperties.getNotify_url());
        aliPayConfig.setSandbox(true);//默认不是沙箱模式

        //支付类, 所有方法都在这个类里
        BestPayServiceImpl bestPayService = new BestPayServiceImpl();
        bestPayService.setAliPayConfig(aliPayConfig);

        //发起支付
        PayRequest payRequest = new PayRequest();
        payRequest.setPayTypeEnum(BestPayTypeEnum.ALIPAY_PC);
        payRequest.setOrderId(order.getOrderNo());
        payRequest.setOrderName(order.getSubject());
        payRequest.setOrderAmount(order.getTotalAmount().doubleValue());
        PayResponse pay = bestPayService.pay(payRequest);

        String form = pay.getBody();
        response.setContentType("text/html;charset=" + alipayProperties.getCharset());
        response.getWriter().write(form); // 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * 封装客户端请求
     */
    public void alipayClient(Order order, HttpServletResponse response) throws Exception {

        AlipayClient client = new DefaultAlipayClient(
                alipayProperties.getUrl(),
                alipayProperties.getAppid(),
                alipayProperties.getRsa_private_key(),
                alipayProperties.getFormat(),
                alipayProperties.getCharset(),
                alipayProperties.getAlipay_public_key(),
                alipayProperties.getSigntype() );

        //发起支付请求
        AlipayTradePagePayRequest alipayRequest=new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturn_url());
        alipayRequest.setNotifyUrl(alipayProperties.getNotify_url());
        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setProductCode("FAST_INSTANT_TRADE_PAY");//设置销售产品码
        model.setOutTradeNo(order.getOrderNo()); //设置订单号
        model.setSubject(order.getSubject()); //设置订单名称
        model.setTotalAmount(order.getTotalAmount().toString()); //设置总金额
        model.setBody(order.getBody()); //设置商品描述
        alipayRequest.setBizModel(model);

        //生成表单
        String form = client.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=" + alipayProperties.getCharset());
        response.getWriter().write(form); // 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * 支付宝服务器异步通知
     * @param request
     * @throws AlipayApiException
     */
    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest request) throws AlipayApiException {
        log.info("异步通知nofityUrl");
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
            log.info("name:"+name+",valueStr:"+valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipay_public_key(), alipayProperties.getCharset(), alipayProperties.getSigntype()); //调用SDK验证签名

        //商户订单号
        String out_trade_no = request.getParameter("out_trade_no");
        //交易状态
        String trade_status = request.getParameter("trade_status");

        //验证成功，更新订单信息
        if(signVerified) {
            if(trade_status.equals("TRADE_FINISHED")){
                log.info("【订单已完成】:TRADE_FINISHED");
            }
            if(trade_status.equals("TRADE_SUCCESS")){
                log.info("【订单付款成功】:TRADE_SUCCESS");
            }

            if(!StringUtils.isEmpty(out_trade_no)){
                Order order = orderService.getByOrOrderNo(out_trade_no);
                if(order != null){
                    order.setBuyTime(new Date());
                    order.setIsPay(1);
                    orderService.save(order);
                }
            }
        }else {
            log.info("验证未通过!");
        }
    }

    /**
     * 同步跳转
     * @param request
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping("/returnUrl")
    public ModelAndView returnUrl(HttpServletRequest request) throws AlipayApiException {

        ModelAndView mav = new ModelAndView();
        mav.addObject("title", "同步通知地址");

        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
            log.info("name:"+name+",valueStr:"+valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipay_public_key(), alipayProperties.getCharset(), alipayProperties.getSigntype()); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified){
            mav.addObject("message", "非常感谢，祝您生活愉快!");
        }else {
            mav.addObject("message", "验签失败!");
        }
        mav.setViewName("returnUrl");
        return mav;
    }


}
